package com.keyue.common.jsr303;



import com.keyue.common.jsr303.annotation.ListIntValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义校验注解 -枚举值校验
 *
 * @author fanzhenyu
 * @date 2023-01-15
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListIntValue, Integer> {
    private Set<Integer> set = new HashSet<>();
    // 是否必填
    private boolean require;

    @Override
    public void initialize(ListIntValue constraintAnnotation) {
        for (int i : constraintAnnotation.enumValue()) {
            set.add(i);
        }
        require = constraintAnnotation.require();
    }

    /**
     * 判断是否通过校验
     *
     * @param value   传入的值
     * @param context
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (!require && value == null) {
            return true;
        }
        return set.contains(value);
    }

}
